package com.unionfetch.content_home.ui.account

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.unionfetch.content_home.R
import com.unionfetch.content_home.adapter.AccountInfoListAdapter
import com.unionfetch.content_home.bean.AccountCount
import com.unionfetch.content_home.bean.LiveAccountInfo
import com.unionfetch.content_home.bean.LiveTradeAccount
import com.unionfetch.content_home.bean.MatTradesResps
import com.unionfetch.content_home.bean.TradeAccountModel
import com.unionfetch.content_home.bean.TradeAccountStatus
import com.unionfetch.content_home.bean.UserStatus
import com.unionfetch.content_home.bean.UserType
import com.unionfetch.content_home.bean.change2TradeAccountModel
import com.unionfetch.content_home.contract.AccountContract
import com.unionfetch.content_home.presenter.AccountPresenter
import com.unionfetch.content_home.ui.OpenAccountGuideUtil
import com.unionfetch.content_home.ui.step.SecondStepOpenAccountActivity
import com.unionftech.common.R.string
import com.unionftech.common.base.IUpdate
import com.unionftech.common.base.mvp.annitation.InjectPresenter
import com.unionftech.common.base.mvp.impl.BaseMvpFragment
import com.unionftech.common.bean.ResponseResult
import com.unionftech.common.bean.toast
import com.unionftech.common.common.GlobalInfoManager
import com.unionftech.common.common.bean.SystemUserInfo
import com.unionftech.common.common.bean.UserKYCFileInfo
import com.unionftech.common.common.language.DynamicResourceManager
import com.unionftech.common.utils.LogUtils
import com.unionftech.common.utils.serializable

class LiveAccountListFragment : BaseMvpFragment(), IUpdate,
    AccountContract.ILiveTradeListView,
    AccountContract.IAccountCountView {
    private val mTvGuideText by lazy { mRootView.findViewById<TextView>(R.id.tv_guide_text) }
    private val mTvEmptyText by lazy { mRootView.findViewById<TextView>(R.id.tv_empty_text) }
    private val mLlEmptyContainer by lazy { mRootView.findViewById<LinearLayout>(R.id.ll_empty_container) }
    private val mRvLiveAccount by lazy { mRootView.findViewById<RecyclerView>(R.id.rv_live_account) }
    private val mAccountList = mutableListOf<TradeAccountModel>()
    private lateinit var mAdapter: AccountInfoListAdapter
    private var mCallBack: ((show: Boolean) -> Unit)? = null

    private var mKycFileInfo: UserKYCFileInfo? = null
    private var mLiveAccountInfo: LiveAccountInfo? = null

    @InjectPresenter
    private lateinit var mAccountPresenter: AccountPresenter

    companion object {
        private const val TAG = "LiveAccountListFragment"
        private const val MAX_ACCOUNT_COUNT = 5
        private const val PARAMS_KYC_FILE_INFO = "params_kyc_file_info"

        @JvmStatic
        fun newInstance(kycInfo: UserKYCFileInfo?) = LiveAccountListFragment().apply {
            arguments = Bundle().apply {
                putSerializable(PARAMS_KYC_FILE_INFO, kycInfo)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {}
    }

    override fun obtainIntentData(bundle: Bundle) {
        super.obtainIntentData(bundle)
        mKycFileInfo = bundle.serializable(PARAMS_KYC_FILE_INFO)
    }

    override fun inflaterContentView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_live_account_list, container, false)
    }

    fun setCallBack(callBack: (show: Boolean) -> Unit) {
        mCallBack = callBack
    }

    override fun initData() {
        super.initData()
        mAdapter = AccountInfoListAdapter(mAccountList)
    }

    override fun initLanguageText() {
        super.initLanguageText()
        mTvEmptyText.text = DynamicResourceManager.getString(string.without_live_trade_account)
        mTvGuideText.text = DynamicResourceManager.getString(string.goto_open_account)
    }

    override fun setListener() {
        super.setListener()
        GlobalInfoManager.getInstance().addListener(this)
        mTvGuideText.setOnClickListener(this)
        mAdapter.setChildItemClickListener { view, position ->
            when (view.id) {
                R.id.tv_lever_in_card, R.id.iv_modify_lever_in_card -> {
                    //修改杠杆
                    mAccountList.getOrNull(position)?.also { tradeAccountModel ->
                        if (tradeAccountModel.status != TradeAccountStatus.DISABLE) {
                            ModifyLiveLeverActivity.startThis(mContext, tradeAccountModel.tradeNo)
                        }
                    }
                }

                R.id.ll_deposit_container -> {
                    //入金
                }
            }
        }
    }

    override fun setView() {
        super.setView()
        hideTitleBar()
        setupRecyclerView()
        loadData()
    }

    private fun setupRecyclerView() {
        mRvLiveAccount.layoutManager =
            LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false)
        mRvLiveAccount.adapter = mAdapter
    }

    override fun doClick(v: View?) {
        super.doClick(v)
        when (v?.id) {
            R.id.tv_guide_text -> {
                gotoOpenAccountStep()
            }
        }
    }

    private fun gotoOpenAccountStep() {
        val userInfo = GlobalInfoManager.getInstance().getSystemUserInfo()
        userInfo?.also { info ->
            val mIsIB = info.type == UserType.IB.type
            if (mIsIB) {
                gotoIBOpenAccount()
            } else {
                gotoRCOpenAccount(info)
            }
        }
    }

    private fun gotoRCOpenAccount(info: SystemUserInfo) {
        if (info.status < UserStatus.USER_WAITTING.status) {
            //1.开户步骤没有完成
            OpenAccountGuideUtil.gotoOpenAccountStep()
            mActivity.finish()
            return
        }
        //2.身份证明没完成
        if (TextUtils.isEmpty(info.filesStatus) || info.filesStatus == "00") {
            //POI和POA都没有填写
            OpenAccountGuideUtil.gotoPoiAuth(
                isSupplement = true, isContinuePoa = true
            )
            return
        }
        if (info.filesStatus == "10") {
            //上传地址证明
            OpenAccountGuideUtil.gotoPoaAuth(isSupplement = false)
            return
        }
        //3.身份证明和地址证明都完成上传，判断补料状态
        if (info.filesStatus == "11") {
            gotoFillKYCInfo()
        }
    }

    private fun gotoFillKYCInfo() {
        mKycFileInfo?.also { kycInfo ->
            if (kycInfo.enable) {
                when (kycInfo.supplementTypes) {
                    "1" -> {
                        //补料身份证明
                        OpenAccountGuideUtil.gotoPoiAuth(
                            isSupplement = true, isContinuePoa = false
                        )
                    }

                    "2" -> {
                        //补料地址证明
                        OpenAccountGuideUtil.gotoPoaAuth(isSupplement = true)
                    }

                    "1,2" -> {
                        //补充身份证明和地址证明
                        //如果poi上传完成，则变成上传poa
                        OpenAccountGuideUtil.gotoPoiAuth(
                            isSupplement = true, isContinuePoa = true
                        )
                    }
                }
            }
        }
    }

    private fun gotoIBOpenAccount() {
        SecondStepOpenAccountActivity.startThis(mContext, true)
        mActivity.finish()
    }

    override fun loadData() {
        super.loadData()
        queryLiveAccountList()
    }

    private fun queryLiveAccountList() {
        mAccountList.clear()
        val userToken = GlobalInfoManager.getInstance().getUserToken()
        mAccountPresenter.getUserLiveAccountList(userToken)
    }

    private fun queryLiveAccountCount() {
        val userToken = GlobalInfoManager.getInstance().getUserToken()
        GlobalInfoManager.getInstance().getSystemUserInfo()?.also { info ->
            mAccountPresenter.queryAccountCount(userToken, info.userId.toString())
        }
    }


    override fun handleUserLiveAccountList(result: ResponseResult<LiveAccountInfo>) {
        if (result.code == ResponseResult.SUCCESS_CODE) {
            queryLiveAccountCount()
            result.data?.also { info ->
                mLiveAccountInfo = info
                info.matTradesResps.also { resps ->
                    updateLiveAccountList(resps)
                }
            }
        } else {
            result.toast()
            LogUtils.d(TAG, "handleUserLiveAccountList error->$result")
        }
    }

    override fun handleAccountCount(response: ResponseResult<AccountCount>) {
        if (response.code == ResponseResult.SUCCESS_CODE) {
            response.data?.also { accountCount ->
                val total = mAccountList.size + accountCount.total
                //检查真实账号是否到达上限
                val hide = total == MAX_ACCOUNT_COUNT
                mCallBack?.invoke(!hide)
            }
        } else {
            response.toast()
            LogUtils.d(TAG, "handleAccountCount error->$response")
        }
    }

    private fun updateLiveAccountList(resps: MatTradesResps) {
        val list = mutableListOf<LiveTradeAccount>()
        list.addAll(resps.running)
        list.addAll(resps.readOnly)
        list.addAll(resps.disable)
        list.addAll(resps.archived)
        if (list.isEmpty()) {
            mRvLiveAccount.visibility = View.GONE
            mLlEmptyContainer.visibility = View.VISIBLE
            mTvEmptyText.text = DynamicResourceManager.getString(string.without_live_trade_account)
            mTvGuideText.visibility = View.VISIBLE
            mTvGuideText.text = DynamicResourceManager.getString(string.goto_open_account)
            updateAccountState()
        } else {
            mRvLiveAccount.visibility = View.VISIBLE
            mLlEmptyContainer.visibility = View.GONE
        }
        for (liveTradeAccount in list) {
            val accountModel = liveTradeAccount.change2TradeAccountModel()
            mAccountList.add(accountModel)
        }
        mAdapter.notifyDataSetChanged()
    }

    private fun updateAccountState() {
        val userInfo = GlobalInfoManager.getInstance().getSystemUserInfo()
        userInfo?.also { info ->
            val isIb = userInfo.type == UserType.IB.type
            if (isIb) {
                updateIBAccountState(userInfo)
            } else {
                updateRCAccountState(info)
            }
        }
    }

    private fun updateRCAccountState(info: SystemUserInfo) {
        if (info.status == UserStatus.USER_WAITTING.status) {
            mTvGuideText.visibility = View.GONE
            mTvEmptyText.text =
                DynamicResourceManager.getString(string.account_audit_please_goto_demo)
        } else if (info.status == UserStatus.USER_FAILURE.status) {
            mTvGuideText.visibility = View.GONE
            mTvEmptyText.text = DynamicResourceManager.getString(string.account_audit_failed)
        }
    }

    private fun updateIBAccountState(userInfo: SystemUserInfo) {
        if (!userInfo.hasAccount && userInfo.hasAudit) {
            //没有交易账号,有在审核中的交易账号(审核中)
            //审核中
            mTvGuideText.visibility = View.GONE
            mTvEmptyText.text =
                DynamicResourceManager.getString(string.account_audit_please_goto_demo)
        }
    }

    fun getHaveAuditMainAccount(): Boolean {
        mLiveAccountInfo?.also { info ->
            return !info.buttonStatus && mAccountList.size == 1
        }
        return false
    }

    override fun onUpdate(obj: Any?) {
        if (obj is Int) {
            if (obj == GlobalInfoManager.UPDATE_LIVE_LIST) {
                loadData()
            }
        }
    }

    override fun onDestroy() {
        GlobalInfoManager.getInstance().remove(this)
        super.onDestroy()
    }


}